<template>
  <el-dialog
    :visible="visible"
    :before-close="handleCloseDialog"
    title="批量导入学生信息"
    width="30%">
    <div>
      <!--accept定义接收的文件类型,这里只接受图片-->
      <input id="fileinput" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" type="file" @change="uploading($event)">
      <br>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit($event)">点击上传</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { importUserInfo } from '@/api/user'

export default {
  name: 'UploadFile',
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      file: '',
      src: ''
    }
  },
  methods: {
    uploading(event) {
      this.file = event.target.files[0] // 获取文件

      var windowURL = window.URL || window.webkitURL

      this.file = event.target.files[0]

      // 创建图片文件的url
      this.src = windowURL.createObjectURL(event.target.files[0])
    },
    handleCloseDialog() {
      this.$emit('close')
    },
    submit() {
      event.preventDefault() // 取消默认行为
      const formdata = new FormData()
      formdata.append('file', this.file)
      // 此处必须设置为  multipart/form-data

      importUserInfo(formdata).then(res => {
        let type = 'error'
        if (res.code === 200) {
          type = 'success'
          this.$emit('importSuccess')
          this.$emit('close')
        }
        this.$message({ type, message: res.msg })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>

</style>
